package com.qianfeng.smartdevices.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qianfeng.smartdevices.cache.AreasCache;
import com.qianfeng.smartdevices.dto.ResultCode;
import com.qianfeng.smartdevices.event.UpdateAreaCacheEvent;
import com.qianfeng.smartdevices.exceptions.AddErrorException;
import com.qianfeng.smartdevices.exceptions.DeleteErrorException;
import com.qianfeng.smartdevices.exceptions.MybaseException;
import com.qianfeng.smartdevices.exceptions.UpdateErrorException;
import com.qianfeng.smartdevices.mapper.AreaMapper;
import com.qianfeng.smartdevices.pojo.Areas;
import com.qianfeng.smartdevices.pojo.CheckStatus;
import com.qianfeng.smartdevices.service.AreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class AreaServiceImpl implements AreaService {

    private AreaMapper areaMapper;

    private AreasCache areasCache;

    private ApplicationContext context;

    @Autowired
    public void setAreasCache(AreasCache areasCache) {
        this.areasCache = areasCache;
    }

    @Autowired
    public void setContext(ApplicationContext context) {
        this.context = context;
    }

    @Autowired
    public void setAreaMapper(AreaMapper areaMapper) {
        this.areaMapper = areaMapper;
    }

    @Override
    public List<Areas> findParentAreaByStatus(Long stauts) {
        return areaMapper.findParentAreaByStatus(stauts);
    }

    @Override
    public void addArea(Areas areas) throws Exception {
        if (areas.isNull(CheckStatus.ADD)) {
            throw new AddErrorException("添加的数据不能为空", ResultCode.DATA_NOT_ALLOW_NUL);
        }
        areaMapper.addArea(areas);
        context.publishEvent(new UpdateAreaCacheEvent());//发布事件
    }

    @Override
    public PageInfo<Areas> findAllAreasByNameLikeAndStatusEquals(int page, int limit, String areaname, Long status, Long parentid) {
        PageHelper.startPage(page, limit);
//        List<Areas> areasList = areaMapper.findAllAreasByNameLikeAndStatusEquals(areaname, status,parentid);
//        return new PageInfo<>(areasList);
        List<Areas> areasList = areasCache.getAllData();//从缓存中获取数据
        List<Areas> subList = areasList.stream().filter(areas -> {
            boolean b1 = ObjectUtils.isEmpty(areaname) ? true : areas.getAreaname().contains(areaname);
            boolean b2 = (ObjectUtils.isEmpty(status) || status == -100) ? true : areas.getStatus().equals(status);
            boolean b3 = (ObjectUtils.isEmpty(parentid) || parentid == -100) ? true : parentid.equals(areas.getParentid());
            return b1 && b2 && b3;
        }).collect(Collectors.toList());
        List<Areas> list = subList.stream().skip((page - 1) * limit).limit(limit).collect(Collectors.toList());
        PageInfo<Areas> pageInfo = new PageInfo<>(list);
        pageInfo.setTotal(subList.size());
        return pageInfo;
    }

    @Override
    public void updateArea(Areas areas) {

        if (areas.isNull(CheckStatus.UPDATE)) {
            throw new UpdateErrorException("更新数据为空", ResultCode.DATA_NOT_ALLOW_NUL);
        }
        areaMapper.updateArea(areas);
        context.publishEvent(new UpdateAreaCacheEvent());

    }

    @Override
    public void deleteAreaById(Long[] ids) {
        if (ids == null || ids.length == 0) {
            throw new DeleteErrorException("没有删除任何东西", ResultCode.DATA_NOT_ALLOW_NUL);
        }
        areaMapper.deleteAreaById(Arrays.asList(ids));
        context.publishEvent(new UpdateAreaCacheEvent());
    }

    @Override
    public Areas getAreaById(Long id) {

        return areasCache.get(id);
    }

    @Override
    public List<Areas> getAreaByParentId(Long id) {
        if (id == null || id == 0) {
            throw new MybaseException("没有传递 id", ResultCode.DATA_NOT_ALLOW_NUL);
        }

        try {
            // List<Area> areaList = areaMapper.getAreaByParentId(id);
            List<Areas> allData = areasCache.getAllData();//从缓存查询所有数据
            List<Areas> areaList = allData.stream().filter(area -> id == area.getParentid()).collect(Collectors.toList());//获取父id和当前id一样的数据
            return areaList;
        } catch (Exception e) {
            e.printStackTrace();
            throw new MybaseException("查询失败", ResultCode.ERROR);

        }
    }
}
